package com.zou.music_downloader;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;

import com.zou.music_downloader.adapter.HistoryAdapter;
import com.zou.music_downloader.bean.DataBean;
import com.zou.music_downloader.sqlite.MyDao;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.List;


@EFragment(R.layout.fragment_history)
public class HistoryFragment extends Fragment {


    @ViewById(R.id.rcv_history)
    public        RecyclerView   recyclerView;
    private       List<DataBean> datas;
    public static HistoryAdapter historyAdapter;
    private       MyDao          myDao;

    @AfterViews
    void afterViews() {
        myDao = new MyDao(getActivity());

        registerBoradcastReceiver();
        datas = new ArrayList<>();
        historyAdapter = new HistoryAdapter(getContext(), datas);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(historyAdapter);


        initDatas();
    }

    private void initDatas() {
        datas.clear();
        datas.addAll(myDao.getDatas());
        historyAdapter.notifyDataSetChanged();
        Log.e("wocao", "initDatas: " + myDao.getDatas().size());
    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
//                收到完成广播后对数据库进行操作
//                获取到downloadId;
                long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
                myDao.updateData(id, "已下载");
                initDatas();
            }
        }
    };

    public void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        //注册广播
        getActivity().registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    public void unRegist() {
//        解除广播
        getActivity().unregisterReceiver(mBroadcastReceiver);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        unRegist();
    }
}
